<template>
    <div class="score-overview">
      <div class="rank-change" id="Homework-quality">
         <h3 class="header-with-select" style="margin-top:0;">作业题量</h3>
         <el-table 
          :data="homeworksavelist" 
          border 
          stripe
          :header-cell-style="{ background: '#e8f0fa', color: '#2A303B', fontWeight: '500' }"
          class="custom-table"
          tooltip-effect="dark"
          style="width: 100%">
          
          <!-- 固定列：年级/班级 -->
          <el-table-column 
            prop="name" 
            label="年级/班级" 
            align="center" 
            fixed="left" />
          
          <!-- 动态列：每个考试时间的提交率 -->
          <el-table-column 
            v-for="(exam, index) in examList" 
            :key="exam.examTime"
            :label="exam.examTime" 
            align="center">
            <template #default="{ row }">
              {{ getSubmitRate(row, exam.examTime) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="rank-change" id="Test-score-rate" v-if="ComparisonReliabilityValidity&&ComparisonReliabilityValidity.length>0">
         <h3 class="header-with-select">信度/效度对比</h3>
        <el-table :data="ComparisonReliabilityValidity" border
        stripe
        :header-cell-style="{ background: '#e8f0fa', color: '#2A303B',fontWeight:'500' }"
        class="custom-table"
        tooltip-effect="dark"
        style="width: 100%">
          <el-table-column prop="name" label="年级/班级" align="center"/>
          <el-table-column prop="name" label="2024年12月16日" align="center">
            <el-table-column prop="name" label="信度" align="center"/>
            <el-table-column prop="name" label="效度 " align="center"/>
          </el-table-column>
          <el-table-column prop="name" label="2024年12月16日" align="center">
            <el-table-column prop="name" label="信度" align="center"/>
            <el-table-column prop="name" label="效度 " align="center"/>
          </el-table-column>
          <el-table-column prop="name" label="2024年12月16日" align="center">
            <el-table-column prop="name" label="信度" align="center"/>
            <el-table-column prop="name" label="效度 " align="center"/>
          </el-table-column>
        </el-table>
      </div>
      <div class="rank-change" id="Test-knowledge-rate">
        <h3 class="header-with-select">知识点改进效果图折线图与图表（选择知识点/章节）</h3>
        <div class="knowledge-select">
          <span>{{startTime}}-{{endTime}}各班得分率情况</span>
          <el-select v-model="knowledgedata" @change="knowledgedatachange">
            <el-option
              v-for="item in knowledgeechartdatalist"
              :key="item.knowledgeName"
              :label="item.knowledgeName"
              :value="item.knowledgeName">
            </el-option>
          </el-select>
        </div>
        <div ref="chartRef" class="echart" style="width: 100%; height: 400px" v-if="knowledgeechartdatalist.length>0"></div>
        <div v-else style="line-height: 60px;width:100%;color: #909399;text-align: center;font-size:14px;">暂无数据</div>
      </div>
      <div class="rank-change" id="Small-question-analysis">
         <h3 class="header-with-select">图表数据</h3>
        <el-table :data="knowledgeechartdatalist" border
        stripe
         :height="knowledgeechartdatalist.length > 5 ? '504px' : undefined"
        :header-cell-style="{ background: '#e8f0fa', color: '#2A303B',fontWeight:'500' }"
        class="custom-table"
        tooltip-effect="dark"
        style="width: 100%">
        <el-table-column 
            label="作业名称" 
            align="center">
            <template slot-scope="{ row }">
              {{ row.knowledgeDataList[0]?.examName || '--' }}
            </template>
          </el-table-column>
          <template v-if="knowledgeechartdatalist.length > 0 && knowledgeechartdatalist[0].knowledgeDataList[0]?.classKnowledgeList">
            <el-table-column 
              v-for="(classItem, index) in knowledgeechartdatalist[0].knowledgeDataList[0].classKnowledgeList"
              :key="classItem.classId"
              :label="`${classItem.className}班得分率`"
              align="center">
              <template slot-scope="{ row }">
                {{ row.knowledgeDataList[0]?.classKnowledgeList[index]?.scoreRate || '--' }}
              </template>
            </el-table-column>
          </template>
          <!-- <el-table-column 
						v-for="(question, index) in knowledgeechartdatalist[0].knowledgeDataList.classKnowledgeList || []"
						:key="question.className"
						:label="question.className+'班得分率'">
              <template slot-scope="scope">
                  {{ scope.row.knowledgeDataList.classKnowledgeList[index].scoreRate }}
              </template>
          </el-table-column> -->
      </el-table>
    </div>
  </div>
</template>

<script>
import { homeworksaveDate, knowledgeechartdata } from '@/api/grade'
import * as echarts from 'echarts'
export default {
  name: 'ScoreOverview',
  data () {
    return {
      subjectId: 0,
      gradeId: 0,
      classIds: [],
      startTime: '',
      endTime: '',
      homeworksavelist: [],
      knowledgeechartdatalist: [],
      ComparisonReliabilityValidity: [],
      chartInstance: null,
      knowledgedata: ''
    }
  },

  methods: {
    //作业提交情况
    async homeworkdataapi () {
      try {
        const res = await homeworksaveDate(
          Number(this.subjectId),
          Number(this.gradeId),
          String(this.classIds),
          String(this.startTime),
          String(this.endTime)
        )
        // console.log('res 是否是 Promise:', res); // 应该是 false
        if (res.code === 200) {
          this.homeworksavelist = res.data
        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        // console.error('加载成绩概览失败:', error)
        throw error  // 向上传递错误，让 loadData 统一处理
      }
    },
    // 根据考试时间获取对应提交率
    getSubmitRate (row, examTime) {
      // console.info('row', row)
      const exam = row.submitStatisticsDTOList.find(item => item.examTime === examTime);
      // console.info(exam)
      return exam ? exam.questionNumber : '-';
    },
    async knowledgeechartdataapi () {
      try {
        const res = await knowledgeechartdata(
          Number(this.subjectId),
          Number(this.gradeId),
          String(this.classIds),
          String(this.startTime),
          String(this.endTime)
        )
        // console.log('res 是否是 Promise:', res); // 应该是 false
        if (res.code === 200) {
          this.knowledgeechartdatalist = res.data
          this.knowledgedata = res.data[0].knowledgeName
          this.$nextTick(() => {
            this.updateChart(res.data[0].knowledgeDataList)
          });

        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        // console.error('加载成绩概览失败:', error)
        throw error  // 向上传递错误，让 loadData 统一处理
      }
    },
    // initChart() {
    //   this.chartInstance = echarts.init(this.$refs.chartRef)
    // },
    knowledgedatachange (val) {
      // console.info(val)
      let knowledgelist = this.knowledgeechartdatalist.filter(item => item.knowledgeName === val)
      this.$nextTick(() => {
        this.updateChart(knowledgelist[0].knowledgeDataList)
      });
    },
    updateChart (data) {
      console.info('data', data);

      // 检查 DOM 元素是否存在
      if (!this.$refs.chartRef) {
        // console.warn('Chart ref not found');
        return;
      }

      // 初始化 ECharts 实例
      if (!this.chartInstance) {
        this.chartInstance = echarts.init(this.$refs.chartRef);
      }

      // 获取第一个知识点名称（假设所有数据项有相同的knowledgeName）
      const knowledgeName = data[0].knowledgeName || '知识点';
      // console.info(knowledgeName)
      // 3. 数据处理
      const examNames = data.map(item => item.examName);
      const classNames = [];
      const seriesData = [];

      // 提取所有班级名称
      data.forEach(exam => {
        exam.classKnowledgeList.forEach(cls => {
          if (!classNames.includes(cls.className)) {
            classNames.push(cls.className);
          }
        });
      });

      // 构建系列数据
      classNames.forEach(clsName => {
        const clsData = data.map(exam => {
          const cls = exam.classKnowledgeList.find(c => c.className === clsName);
          return cls ? parseFloat(cls.scoreRate) : 0;
        });

        seriesData.push({
          name: `${clsName}班`,
          type: 'line',
          data: clsData,
          smooth: true
        });
      });

      const option = {
        title: {
          text: `${knowledgeName}得分率分析`,
          left: 'center',
          top: 10
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: params => {
            let result = `${params[0].axisValue}<br>`;
            params.forEach(param => {
              result += `${param.seriesName}: ${param.value}%<br>`;
            });
            return result;
          }
        },
        legend: {
          data: seriesData.map(item => item.name),
          top: 40
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: examNames,
          axisLabel: {
            interval: 0,
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '得分率(%)',
          min: 0,
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: seriesData,
        color: ['#295CFF', '#FF7D00', '#00B42A']
      };

      this.chartInstance.setOption(option);

      // 窗口大小变化时重新调整图表大小
      window.addEventListener('resize', () => {
        if (this.chartInstance) {
          this.chartInstance.resize();
        }
      });
    },
    handleSegmentChange () {
      // 分段改变时需要重新加载
      this.hasLoaded = false;
      this.scorerangeTable()
    },

    handleResize () {
      this.chartInstance.resize()
    }
  },
  mounted () {
    this.subjectId = Number(this.$route.query.subjectid) || 0
    this.gradeId = Number(this.$route.query.gradeid) || 0
    // this.classIds = (this.$route.query.classids || '').split(',').map(Number)
    this.classIds = this.$route.query.classids || ''
    this.startTime = this.$route.query.startTime || ''
    this.endTime = this.$route.query.endTime || ''
    this.homeworkdataapi() // 作业提交情况
    this.knowledgeechartdataapi()
  },
  computed: {
    // 提取所有考试时间（去重）
    examList () {
      if (!this.homeworksavelist.length) return [];
      const exams = new Map();
      this.homeworksavelist[0].submitStatisticsDTOList.forEach(item => {
        exams.set(item.examTime, item);
      });
      return Array.from(exams.values());
    }
  },
}
</script>

<style scoped>
.score-overview {
  background: #FFFFFF;
  box-shadow: 0 12px 16px 0 #5572921a;
  border-radius: 10px;
  padding: 24px;
}

.query-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.query-form {
  display: flex;
  align-items: center;
}

.overview-section,
.score-details,
.score-analysis,
.rank-change,
.error-questions {
  background: #fff;
  border-radius: 4px;
}

.overview-content {
  box-sizing: border-box;
  background: #295cff0a;
  border: 1px solid #295cff33;
  border-radius: 10px;
  padding: 18px 24px 0;
  font-size: 14px;
}

.submit-info {
  margin-bottom: 16px;
  line-height: 1.8;
  color: #8E96A4
}

.submit-info span {
  color: #295CFF
}

.submit-info i {
  color: #5B6371;
  font-style: normal;
}

.submit-info b {
  font-style: normal;
  font-weight: normal;
}

.class-info {
  margin-top: 8px;
  text-indent: 2em;
  line-height: 1.8;
}

.score-row {
  display: flex;
  gap: 16px;
  justify-content: center;
}

.score-item {
  min-width: 40px;
  text-align: center;
}

.question-numbers {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 8px;
  font-size: 12px;
}

.question-numbers span {
  min-width: 40px;
  text-align: center;
}

.rank-change {
  background: #fff;
  border-radius: 4px;
}

.change-info {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.change-info .el-tag {
  min-width: 80px;
}

.error-questions {
  background: #fff;
  border-radius: 4px;
}

.el-tag {
  width: 80px;
  text-align: center;
}

.analysis-content {
  margin-top: 16px;
  line-height: 1.8;
}

.header-with-select {
  font-size: 16px;
  color: #2A303B;
  margin-bottom: 14px;
  margin-top: 24px;
}

.custom-table {
  width: 100%;
  border: 1px solid rgba(216, 228, 240, 1);
  border-radius: 10px;
  border-right: none;
  border-bottom: none;
}

/* 自定义表格内部元素的样式 */
.custom-table>>>.el-table__header-wrapper th {
  background-color: rgb(232, 240, 250);
  height: 42px;
  padding: 0;
  text-align: center;
  font-weight: normal
}

.custom-table>>>.el-table__row td {
  height: 42px;
  padding: 0;
  text-align: center;
  border-bottom: none;
  border-right: solid 1px rgba(216, 228, 240, 1);
}

.el-table .warning-row {
  background: #ffffff;
}

.el-table .success-row {
  background: #D8E4F0;
}

.knowledge-select {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.knowledge-select span {
  width: 357px;
  height: 29px;
  background: #fffbf7;
  border: 1px solid rgba(255, 89, 41, 0.06);
  border-radius: 10px;
  font-size: 14px;
  color: rgba(123, 128, 138, 1);
  text-align: center;
  line-height: 29px;
}

.knowledge-select>>>.el-select {
  height: 29px;
  background: rgba(76, 112, 255, 0.8);
  border-radius: 10px;
}

.knowledge-select>>>.el-input__inner {
  height: 29px;
  background: rgba(76, 112, 255, 0.8);
  border-radius: 10px;
  color: #fff !important;
  font-size: 12px;
  border: none;
}

.knowledge-select>>>.el-input__icon {
  line-height: 29px;
}
</style>